package com.chookss.home.publish;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aliyun.svideo.common.utils.NetUtils;
import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.base.StaticClass;
import com.chookss.home.entity.NewsEntiry;
import com.chookss.tools.GridSpacingItemDecoration;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.PathUtil;
import com.chookss.tools.PermissionUtils;
import com.chookss.tools.Utils;
import com.chookss.view.GlideEngine;
import com.chookss.view.ImageFileCompressEngine;
import com.chookss.view.MyRoundLayout;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.lvgroup.hospital.base.BaseAct;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.interfaces.OnCancelListener;
import com.lxj.xpopup.interfaces.OnConfirmListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class PublishNewsActivity extends BaseAct {
    @BindView(R.id.edTitle)
    EditText edTitle;
    @BindView(R.id.common_title_txt)
    TextView common_title_txt;
    @BindView(R.id.edContent)
    EditText edContent;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tvLocation)
    TextView tvLocation;
    @BindView(R.id.ivBg)
    View ivBg;
    @BindView(R.id.ivChoice)
    ImageView ivChoice;
    @BindView(R.id.ivChoice2)
    ImageView ivChoice2;
    private MyImagsAdapter adapter;
    private List<String> list = new ArrayList<>();
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private int shareFlag = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_news);
        ButterKnife.bind(this);
        initState();
    }

    @Override
    public void initData() {
        NavigationTools.saveUseRecord(this, "2", "11");
        common_title_txt.setText("发布");
        String init = new ShareUtils().getString(this, StaticClass.USER_NICKNAME, "") + " " + Utils.getCurrentTime() + "的新闻";
        edTitle.setText(init);
        list.add("");
        GridLayoutManager gridLayoutManager1 = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(gridLayoutManager1);
        GridSpacingItemDecoration gridSpacingItemDecoration = new GridSpacingItemDecoration(3, Utils.dip2px(this, 12), false);
        recyclerView.addItemDecoration(gridSpacingItemDecoration);
        adapter = new MyImagsAdapter(R.layout.item_my_news, this, list);
        recyclerView.setAdapter(adapter);
        if (NetUtils.isGPSEnabled(this)) {
            getPermissions();
        } else {
            showDialog();
        }
    }
    private void showDialog() {
        new XPopup.Builder(this)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(false)
                .asConfirm("提示", "定位服务未开启，请打开定位服务",
                        "取消", "去开启",
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivity(intent);
                                finish();
                            }
                        }, new OnCancelListener() {
                            @Override
                            public void onCancel() {
                                finish();
                            }
                        }, false)
                .show();
    }
    private void startLoc() {
        //声明LocationClient类
        try {
            if(mLocationClient==null){
                LocationClient.setAgreePrivacy(true);
                mLocationClient = new LocationClient(getApplicationContext());
                LocationClientOption option = new LocationClientOption();
                mLocationClient.registerLocationListener(myListener);
                option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
                option.setCoorType("bd09ll");
                option.setIsNeedAddress(true);
                option.setOpenGps(true);
                option.setScanSpan(1000);
                mLocationClient.setLocOption(option);
            }
            if(mLocationClient != null) {
                mLocationClient.start();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getPermissions() {
        XXPermissions.with(this)
                // 申请单个权限
                .permission(Permission.ACCESS_FINE_LOCATION)
                .permission(Permission.ACCESS_COARSE_LOCATION)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if (all) {
                           startLoc();
                        } else {
                            MyToast.show("定位权限未正常授予");
                        }
                    }

                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        if (never) {
                            MyToast.show("被永久拒绝授权，请手动授予定位权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(PublishNewsActivity.this, permissions);
                        } else {
                            MyToast.show("获取定位权限失败");
                        }
                    }
                });
    }

    private int locationFlag = 0;

    @OnClick({R.id.common_title_back, R.id.rlDelete, R.id.rlChoice, R.id.tvChoieLocation, R.id.tv_publish})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_title_back:
                finish();
                break;
            case R.id.rlDelete:
                edTitle.setText("");
                break;
            case R.id.tvChoieLocation:
                getPermissions();
                break;
            case R.id.rlChoice:
                if (ivBg == null) {
                    return;
                }
                if (shareFlag == 1) {
                    shareFlag = 0;
                    ivBg.setVisibility(View.GONE);
                    ivChoice.setVisibility(View.GONE);
                    ivChoice2.setVisibility(View.VISIBLE);
                } else {
                    shareFlag = 1;
                    ivBg.setVisibility(View.VISIBLE);
                    ivChoice.setVisibility(View.VISIBLE);
                    ivChoice2.setVisibility(View.GONE);
                }
                break;
            case R.id.tv_publish:
                if (Urls.antiShake.check()) {
                    return;
                }
                if (edTitle == null) {
                    return;
                }
                if (Utils.isNull(edTitle.getText().toString().replace(" ", ""))) {
                    MyToast.show("请输入标题");
                    return;
                }
                if (Utils.isNull(edContent.getText().toString().replace(" ", ""))) {
                    MyToast.show("请输入正文");
                    return;
                }
                if (list.size() == 9) {
                    //删除最后一个+  第九个正好是+不用处理
                    if (Utils.isNull(list.get(8))) {
                        list.remove(list.size() - 1);
                    }
                } else {
                    //删除最后一个+
                    if (list.size() < 10) {
                        list.remove(list.size() - 1);
                    }
                }

                NewsEntiry newsEntiry = new NewsEntiry();
                Intent intent = new Intent(this, UploadNewsService.class);
                newsEntiry.setNewsTitle(edTitle.getText().toString());
                newsEntiry.setNewsContent(edContent.getText().toString());
                newsEntiry.setNewsLocation(tvLocation.getText().toString());
                newsEntiry.setShareFlag(shareFlag + "");
                List<NewsEntiry.PicturesBean> picList = new ArrayList<>();
                newsEntiry.setPictures(picList);
                if (list.size() > 0) {
                    for (int i = 0; i < list.size(); i++) {
                        NewsEntiry.PicturesBean picturesBean = new NewsEntiry.PicturesBean();
                        picturesBean.setPicturePath(list.get(i));
                        newsEntiry.getPictures().add(picturesBean);
                        if (i == list.size() - 1) {
                            intent.putExtra("newsEntiry", newsEntiry);
                            startService(intent);
                            finish();
                        }
                    }
                    KLog.i("----" + newsEntiry.getPictures().size());
                } else {
                    intent.putExtra("newsEntiry", newsEntiry);
                    startService(intent);
                    finish();
                }


                break;
        }
    }

    private void requestCamera() {
        XXPermissions.with(this)
                .permission(Permission.CAMERA)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> granted, boolean all) {
                        if (all) {

                            openCamera(10 - list.size());
                        }
                    }

                    @Override
                    public void onDenied(List<String> denied, boolean quick) {
                        PermissionUtils.errorPermission(PublishNewsActivity.this, denied, quick);
                    }
                });
    }

    private void openCamera(int num) {
        PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .isDisplayCamera(true)//是否显示相机入口
                .setMaxSelectNum(num)
                .setSelectionMode(SelectModeConfig.MULTIPLE)//多选
                .isPreviewImage(true)//是否支持预览图片
                .setCompressEngine(ImageFileCompressEngine.createGlideEngine())
                .setRecyclerAnimationMode(AnimationType.SLIDE_IN_BOTTOM_ANIMATION)
                .setImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == PictureConfig.CHOOSE_REQUEST) {
                // 如果是直接从相册获取
                List<LocalMedia> selectList = PictureSelector.obtainSelectorList(data);
                for (int i = 0; i < selectList.size(); i++) {
                    KLog.i("压缩::" + selectList.get(0).getCompressPath());
                    KLog.i("原图::" + selectList.get(0).getPath());

                    String url = "";
                    if (!Utils.isNull(selectList.get(i).getCompressPath())) {
                        if (selectList.get(i).getCompressPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getCompressPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getCompressPath();
                        }
                    } else {
                        if (selectList.get(i).getPath().contains("content://")) {
                            Uri uri = Uri.parse(selectList.get(i).getPath());
                            url = PathUtil.getPath(this, uri);
                        } else {
                            url = selectList.get(i).getPath();
                        }
                    }

                    KLog.i("Android Q 特有Path::" + url);
                    if (!list.contains(url)) {
                        list.add(0, url);
                    }
                    if (list.size() == 10) {
                        list.remove(9);
                    }
                }
                adapter.notifyDataSetChanged();
            }
        }

    }


    class MyImagsAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Context context;
        private int width, height;

        public MyImagsAdapter(int layoutResId, Context context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
            width = (Utils.getScreenWidthPixel(context) - Utils.dip2px(context, 48)) / 3;
            height = width;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String item) {
            MyRoundLayout myRl = helper.getView(R.id.myRl);
            ImageView ivBg = helper.getView(R.id.ivBg);
            LinearLayout llDelete = helper.getView(R.id.llDelete);
            LinearLayout llAdd = helper.getView(R.id.llAdd);
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) myRl.getLayoutParams();
            params.height = height;
            params.width = width;
            myRl.setLayoutParams(params);
            RelativeLayout.LayoutParams llAddParams = (RelativeLayout.LayoutParams) llAdd.getLayoutParams();
            llAddParams.height = height;
            llAddParams.width = width;
            llAdd.setLayoutParams(llAddParams);
            if (Utils.isNull(item)) {
                llAdd.setVisibility(View.VISIBLE);
                myRl.setVisibility(View.GONE);
            } else {
                llAdd.setVisibility(View.GONE);
                myRl.setVisibility(View.VISIBLE);
                Glide.with(PublishNewsActivity.this).load(item).into(ivBg);
            }
            llDelete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(helper.getItemPosition());
                    if (list.size() < 9 && !Utils.isNull(list.get(list.size() - 1))) {
                        list.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });
            llAdd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestCamera();
                }
            });

        }
    }
    private boolean firstLocation=true;
    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                locationFlag++;
                if (tvLocation == null) {
                    return;
                }
                if (!Utils.isNull(location.getAddrStr())) {
                    tvLocation.setText(location.getAddrStr());
                }else {
                    if(firstLocation){
                        if (mLocationClient != null) {
                            firstLocation=false;
                            mLocationClient.start();
                        }
                    }
                }
                if (locationFlag > 3) {
                    if (null != mLocationClient && mLocationClient.isStarted()) {
                        locationFlag = 0;
                        if(mLocationClient!=null){
                            mLocationClient.stop();
                        }
                    }
                }

            }else {
                if(firstLocation){
                    if (mLocationClient != null) {
                        firstLocation=false;
                        mLocationClient.start();
                    }
                }
            }

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mLocationClient!=null){
            mLocationClient.stop();
        }
    }
}
